package handler

import (
	"context"
	"gozeroSingle/internal/logic"
	"gozeroSingle/internal/types"
	"gozeroSingle/utils"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/rest/httpx"
)

/*
 +----------------------------------------------------------------------
 + Title        : AccountHandler
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2025-10-18
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 账户处理器
 +----------------------------------------------------------------------
*/
type AccountHandler struct {
	BaseHandler
}

/**
 * 新增
 *
 * @param string Username ------------------必传
 * @param string Name ----------------------非必传
 * @param string Mobile --------------------必传
 * @param string Title ---------------------必传
 * @param string note ----------------------非必传
 * @return json
 * @author huwl
 * @date 2025/10/31 19:48:34
 */
func (control *AccountHandler) Add(w http.ResponseWriter, r *http.Request) {
	var req types.AccountAddRequest
	if err := httpx.Parse(r, &req); err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	// 调用逻辑层
	accountLogic := logic.NewAccountLogicInstance(context.Background(), control.SvcCtx)
	err := accountLogic.Add(req)
	if err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(r, w, control.WithMessage("新增账户成功"))
}

/**
 * 账户登录
 *
 * @param string Username ------------------必传
 * @param string Password ------------------必传
 * @return json
 * @author huwl
 * @date 2025/10/31 19:48:34
 */
func (control *AccountHandler) Login(w http.ResponseWriter, r *http.Request) {
	var req types.AccountLoginRequest
	if err := httpx.Parse(r, &req); err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	// 调用逻辑层
	accountLogic := logic.NewAccountLogicInstance(context.Background(), control.SvcCtx)
	result, err := accountLogic.Login(req)
	if err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(r, w, control.WithData(result))
}

/**
 * 账户详情
 *
 * @param uint16 accountId ---------------------非必传,账户Id
 * @return Json
 * @author huwl
 * @date 2025/10/31 12:54:03
 */
func (control *AccountHandler) Detail(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.ParseInt(r.Header.Get("aid"), 10, 64)
	accountId, _ := strconv.ParseInt(utils.DefaultQuery(r, "id", "0"), 10, 64)

	if accountId == 0 {
		accountId = id
	}

	// 调用逻辑层
	accountLogic := logic.NewAccountLogicInstance(context.Background(), control.SvcCtx)
	result, err := accountLogic.Detail(uint16(accountId))
	if err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(r, w, control.WithData(result))
}
